package com.guosen.zebra.gateway.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP 请求工具类
 */
public final class HttpRequestUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtil.class);
    
    private HttpRequestUtil(){}

    /**
     * 获取JSON格式的请求参数
     * @param request   原始HTTP请求
     * @return  JSON格式的请求参数
     */
    public static JSONObject getJSONParam(HttpServletRequest request){
        JSONObject jsonParam;
        try (BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            LOGGER.error("Failed to parse http request", e);
            throw new IllegalArgumentException("Failed to parse http request", e);
        }

        return jsonParam;
    }

    /**
     * 获取HTTP header
     * @param request   原始HTTP请求
     * @return HTTP header
     */
    public static Map<String, String> getHeader(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerKey = headerNames.nextElement();
            String headerValue = request.getHeader(headerKey);
            headers.put(headerKey, headerValue);
        }

        return headers;
    }
}
